package com.company;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @date : 2022-08-26 上午11:07
 * List的循环遍历的时候删除
 */

public class P028_ListLoopRemove {

    public static void main(String[] args) {
        personListRemove();
    }


    private static void personListRemove() {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("张三", 20));
        personList.add(new Person("李四", 21));

        personList.removeIf(person -> "张三".equals(person.getName())
                && person.getAge() == 20);
        System.out.println(personList);
    }

    @Data
    @AllArgsConstructor
    public static class Person {
        private String name;
        private int age;
    }


    private static void stringListRemove() {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Strawberry");

        // 有问题1：遗漏元素
        // for (int i = 0; i < fruits.size(); i++) {
        //     System.out.println(fruits.get(i));
        //     if ("Apple".equals(fruits.get(i))) {
        //         fruits.remove(i);
        //     }
        // }

        // 有问题2：出异常
        // for (String fruit : fruits) {
        //     System.out.println(fruit);
        //     if ("Apple".equals(fruit)) {
        //         fruits.remove(fruit);
        //     }
        // }

        Iterator<String> fruitIterator = fruits.iterator();
        while (fruitIterator.hasNext()) {
            String fruit = fruitIterator.next();
            System.out.println(fruit);
            if ("Apple".equals(fruit)) {
                fruitIterator.remove();
            }
        }
    }
}
